#!/bin/bash
SERVER="./main"
PORT=8080
TEST_DURATION=60  # 测试持续时间(秒)
WARMUP_TIME=5     # 预热时间(秒)

# 启动服务器
$SERVER &
SERVER_PID=$!
sleep 1 # 等待服务器启动

# 定义测试函数
run_test() {
    local concurrency=$1
    local test_name=$2
    
    echo -e "\n===== $test_name 测试 [并发数: $concurrency] ====="
    
    # 预热
    ab -t $WARMUP_TIME -c $concurrency -k http://127.0.0.1:$PORT/ > /dev/null
    
    # 正式测试
    ab -t $TEST_DURATION -c $concurrency -k http://127.0.0.1:$PORT/ > "benchmark_${concurrency}.log"
    
    # 提取关键指标
    grep "Requests per second" "benchmark_${concurrency}.log"
    grep "Time per request" "benchmark_${concurrency}.log" | head -1
    grep "Failed requests" "benchmark_${concurrency}.log"
    grep "Keep-Alive requests" "benchmark_${concurrency}.log"
}

# 执行测试序列
run_test 10 "基础性能"
run_test 100 "中等负载" 
run_test 500 "高并发压力"
run_test 1000 "极限负载"

# 长时稳定性测试 (30分钟)
echo -e "\n===== 长时稳定性测试 ====="
ab -t 1800 -c 100 -k http://127.0.0.1:$PORT/ > benchmark_stability.log

# 资源监控 (后台运行)
sar -u -r -n DEV 1 > system_stats.log &
SAR_PID=$!

# 测试后清理
kill $SERVER_PID
kill $SAR_PID

# 生成报告
echo -e "\n===== 测试报告摘要 ====="
for f in benchmark_*.log; do
    echo -e "\n$f 结果:"
    grep -E "Requests per second|Time per request|Failed requests" $f
done

echo -e "\n稳定性测试结果:"
grep "Requests per second" benchmark_stability.log